package station.VisualComponents;

import java.awt.Color;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.SwingUtilities;

import station.GUI.MainForm;

public class CameraConnectionMakerThread extends Thread {

	private ServerSocket server;
	private MainForm mainForm;
	private boolean shouldStop;
	
	public CameraConnectionMakerThread() {
		 try {
			server = new ServerSocket(4444);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		System.out.println("Listening for connection: started");
		while(!shouldStop){
			try {
				final Socket client = server.accept();
				if (client != null){
					SwingUtilities.invokeLater(new Runnable(){

						@Override
						public void run() {
							if (mainForm.camConnListener == null){
								try {
									mainForm.camConnListener = new CameraConnectionListener();
									mainForm.camConnListener.setMainForm(mainForm);
									mainForm.camConnListener.setIn(new DataInputStream(client.getInputStream()));
									mainForm.camConnListener.start();
									mainForm.lblConnectedCam.setText("Connected");
									mainForm.lblConnectedCam.setForeground(Color.green);
								} catch (IOException e) {
									System.out.println("error opening connection to cam");
								}
							}
						}
						
					});
				}
			} catch (Exception e) {
				System.out.println("error");
			}
		}
	}
	
	public void threadStop(){
		shouldStop = true;
	}

	public void setMainForm(MainForm mainForm) {
		this.mainForm = mainForm;
	}

	
	
}
